package com.example.demo.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.demo.common.Result;
import com.example.demo.entity.UserEntity;
import com.example.demo.mapper.UserMapper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author bueryouth
 */
@RestController
@RequestMapping("/main")
public class MainController {
    @Resource
    UserMapper userMapper;

    /**
     * 登录接口
     */
    @PostMapping("/login")
    public Result<?> login(@RequestBody UserEntity userEntity) {
        UserEntity res = userMapper
            .selectOne(Wrappers.<UserEntity>lambdaQuery().eq(UserEntity::getUsername, userEntity.getUsername())
                .eq(UserEntity::getPassword, userEntity.getPassword()));
        if (res == null) {
            return Result.error("500", "用户名或密码有误");
        }
        return Result.success(res);
    }

    /**
     * 注册接口
     */
    @PostMapping("/register")
    public Result<?> register(@RequestBody UserEntity userEntity) {
        UserEntity res = userMapper
            .selectOne(Wrappers.<UserEntity>lambdaQuery().eq(UserEntity::getUsername, userEntity.getUsername()));
        if (res != null) {
            return Result.error("500", "用户名重复");
        }
        userMapper.insert(userEntity);
        return Result.success();
    }
}
